package com.xindaoapp.happypet.adapter;

import java.util.List;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.api.Address;
import com.xindaoapp.happypet.application.HappyPetApplication;
import com.xindaoapp.happypet.bean.ShoppingCartInfo;
import com.xindaoapp.happypet.utils.CommonParameter.UserState;
import com.xindaoapp.happypet.utils.CommonUtil;
import com.xindaoapp.happypet.utils.Constants;
import com.xindaoapp.happypet.utils.IRequest;

/**
 * 购物车展示数据的adapter
 * 
 * @author xindaoapp
 * 
 */
public class ShoppingCartAdapter extends BaseAdapter {
    private List<ShoppingCartInfo> list;
    private final Context mContext;
    private final IRequest<Integer> iRequest;
    private final boolean isOnlyShowProduct;
    // 用户选中的购物车itemid
    private final String rec_ids;
    // 是否删除购物车商品
    private boolean isDeleteProduct = false;

    public ShoppingCartAdapter(Context context, List<ShoppingCartInfo> list,
            IRequest<Integer> iRequest, boolean isOnlyShowProduct, String rec_ids) {
        super();
        this.list = list;
        mContext = context;
        this.iRequest = iRequest;

        this.isOnlyShowProduct = isOnlyShowProduct;
        this.rec_ids = rec_ids;
    }

    // private void initList() {
    // if(isOnlyShowProduct){
    // checkOutItemList = new ArrayList<ShoppingCartInfo>();
    //
    // for (int i = 0; i < list.size(); i++) {
    // String[] recids = rec_ids.split(",");
    // for (int j = 0; j < recids.length; j++) {
    // if(recids[j].equals(list.get(i).rec_id)){
    // checkOutItemList.add(list.get(i));
    // list.clear();
    // list = checkOutItemList;
    // }
    // }
    // }
    //
    //
    // }
    //
    // }

    public void resetList(List<ShoppingCartInfo> list) {
        this.list = list;

    }

    public void isDeleteProduct(boolean isDeleteProduct) {
        this.isDeleteProduct = isDeleteProduct;
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;

        final ShoppingCartInfo info = (ShoppingCartInfo) getItem(position);
        if (isOnlyShowProduct) {
            int count = 0;
            String[] recids = rec_ids.split(",");
            for (String recid : recids) {
                if (recid.equals(info.rec_id)) {
                    count++;

                }
            }

            if (count < 1) {
                return new View(mContext);
            }
        }

        if (convertView == null) {
            holder = new ViewHolder();
            convertView = LayoutInflater.from(mContext).inflate(R.layout.item_shoppingcart, null);
            holder.name = (TextView) convertView.findViewById(R.id.name);
            holder.state = (TextView) convertView.findViewById(R.id.state);
            holder.icon = (ImageView) convertView.findViewById(R.id.icon);
            holder.count = (TextView) convertView.findViewById(R.id.count);
            holder.price = (TextView) convertView.findViewById(R.id.price);
            holder.u_price = (TextView) convertView.findViewById(R.id.u_price);
            holder.checkBox = (ImageView) convertView.findViewById(R.id.check_box);
            holder.category = (TextView) convertView.findViewById(R.id.category);
            holder.arrow = convertView.findViewById(R.id.arrow);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }



        holder.name.setText(info.goods_name);

        holder.price.setText(String.format(mContext.getString(R.string.price),
                CommonUtil.transitionToFloat(info.goods_price * info.goods_number)));
        holder.u_price.setText(String.format(mContext.getString(R.string.price),
                CommonUtil.transitionToFloat(info.goods_price)));
        // 显示商品规格信息
        if (!TextUtils.isEmpty(info.goods_attr)) {
            holder.category.setVisibility(View.VISIBLE);
            holder.category.setText(info.goods_attr);
        }
        ImageLoader.getInstance().displayImage(info.goods_thumb, holder.icon);

        holder.checkBox.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                info.isChecked = !info.isChecked;
                iRequest.request(0);
                // resetProductCount();
                notifyDataSetChanged();
            }
        });

        if (isOnlyShowProduct) {
            holder.checkBox.setVisibility(View.GONE);
            holder.count.setBackgroundResource(0);
            holder.arrow.setVisibility(View.GONE);
            holder.count.setText(String.valueOf(info.goods_number) + "件");
        } else {
            holder.count.setText(String.valueOf(info.goods_number));
            holder.checkBox.setVisibility(View.VISIBLE);
        }

        if (info.isChecked && !isDeleteProduct) {
            // 用户手动选商品时，添加到集合中
            // if(!checkShoppingList.contains(info)){
            // checkShoppingList.add(info);
            // }
            Address.tittle = info.goods_name;
            convertView.setBackgroundColor(mContext.getResources().getColor(
                    R.color.shopping_cart_checked));
            holder.checkBox.setSelected(true);
        } else {
            // checkShoppingList.remove(info);
            convertView.setBackgroundColor(mContext.getResources().getColor(
                    R.color.shopping_cart_unchecked));
            holder.checkBox.setSelected(false);
        }
        if (position == list.size() - 1) {
            isDeleteProduct = false;
        }

        holder.count.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                showEditCountDialog(info);
            }
        });
        // 单个商品跳转
        // holder.arrow.setOnClickListener(new OnClickListener() {
        // @Override
        // public void onClick(View v) {
        // Intent intent = new Intent(mContext, ProductDetailActivity1.class);
        // intent.putExtra("productId", info.goods_id);
        // mContext.startActivity(intent);
        // }
        // });

        return convertView;
    }

    /**
     * 编辑商品数量填出框
     * 
     * @param info
     */
    private void showEditCountDialog(final ShoppingCartInfo info) {
        EditCountDialog dialog =
                new EditCountDialog(mContext, R.style.Edit_Count_Dialog, info.goods_number,
                        new IRequest<Integer>() {

                            @Override
                            public void request(final Integer t) {
                                editCart(t, info);
                            }
                        });
        dialog.show();
    }

    private int getGoodsAllNum() {
        if (list == null) {
            return 0;
        }
        int count = 0;
        for (ShoppingCartInfo info : list) {
            count = count + info.goods_number;
        }
        return count;
    }

    private void editCart(final int t, final ShoppingCartInfo info) {
        HappyPetApplication
                .get()
                .getMoccaApi()
                .editCart(UserState.getUserUid(), t, info.rec_id,
                        new IRequest<Pair<Boolean, String>>() {

                            @Override
                            public void request(Pair<Boolean, String> r) {
                                if (null != r) {
                                    if (r.first) {
                                        info.goods_number = t;
                                        notifyDataSetChanged();
                                        iRequest.request(0);

                                        // 通知刷新购物车数量
                                        Intent intent = new Intent(Constants.DELETE_CART);
                                        intent.putExtra("goods_number", getGoodsAllNum());
                                        mContext.sendBroadcast(intent);

                                    }
                                    Toast.makeText(mContext, r.second, Toast.LENGTH_SHORT).show();
                                } else {
                                    Toast.makeText(mContext, R.string.net_error, Toast.LENGTH_SHORT)
                                            .show();
                                }
                            }
                        });
    }

    class ViewHolder {
        TextView name;
        ImageView icon;
        ImageView checkBox;
        TextView count;
        TextView state;
        TextView price;
        TextView u_price;
        TextView category;
        View arrow;
    }

    /**
     * 修改数量的对话框
     */
    class EditCountDialog extends Dialog {
        EditText etCount;
        int count;

        private IRequest<Integer> iRequest;

        public EditCountDialog(Context context, IRequest<Integer> iRequest) {
            super(context);
            this.iRequest = iRequest;
        }

        public EditCountDialog(Context context, boolean cancelable, OnCancelListener cancelListener) {
            super(context, cancelable, cancelListener);
        }

        public EditCountDialog(Context context, int theme, int count, IRequest<Integer> iRequest) {
            super(context, theme);
            this.iRequest = iRequest;
            this.count = count;
        }

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.dialog_edit_count);
            etCount = (EditText) findViewById(R.id.count);
            etCount.setText(String.valueOf(count));
            findViewById(R.id.cancel).setOnClickListener(mOnClickListener);
            findViewById(R.id.close).setOnClickListener(mOnClickListener);
            findViewById(R.id.confirm).setOnClickListener(mOnClickListener);
            findViewById(R.id.subtract).setOnClickListener(mOnClickListener);
            findViewById(R.id.plus).setOnClickListener(mOnClickListener);
        }

        private final View.OnClickListener mOnClickListener = new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.confirm:
                        confirm();
                        break;
                    case R.id.close:
                    case R.id.cancel:
                        dismiss();
                        break;
                    case R.id.subtract:
                        subtract();
                        break;
                    case R.id.plus:
                        plus();
                        break;
                    default:
                        break;
                }
            }
        };

        private void confirm() {
            // try catch 防止越界
            int count = 0;
            try {
                count = Integer.parseInt(etCount.getText().toString());
                if (count == 0) {
                    Toast.makeText(mContext, "请输入有效的数量!!!", Toast.LENGTH_SHORT).show();
                } else {
                    iRequest.request(count == 0 ? 1 : count);
                    dismiss();
                }
            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(mContext, "请输入有效的数量!!!", Toast.LENGTH_SHORT).show();
            }
        }

        private void plus() {
            try {
                int etcount = Integer.parseInt(etCount.getText().toString());
                etcount++;
                if (etcount > 0) {
                    etCount.setText(String.valueOf(etcount));
                }
            } catch (Exception e) {
            }
            etCount.setSelection(etCount.getText().toString().length());
        }

        private void subtract() {
            try {
                int etcount = Integer.parseInt(etCount.getText().toString());
                etcount--;
                if (etcount > 0) {
                    etCount.setText(String.valueOf(etcount));
                }
            } catch (Exception e) {
            }
            etCount.setSelection(etCount.getText().toString().length());
        }

    }


}
